﻿// Copyright (c) 2009 Kjetil Eraker Samuelsen
// This source is subject to the Microsoft Public License.
// See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
// All other rights reserved.

using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;

using Ksamuelsen.Services.Vonage;
using OOutlook = Microsoft.Office.Interop.Outlook;


namespace Ksamuelsen.Office.Outlook.Addin.VDialer {
    public class Dialer {
        private static Regex               expr       = (new Regex(Properties.Resources.CONTACT_NUMBER_ALLOWED_CHARS, RegexOptions.Compiled));
        private static Regex               extexpr    = (new Regex(Properties.Resources.CONTACT_NUMBER_EXTENSIONS, RegexOptions.Compiled));
        private static StringUtil.Option[] subjectfmt = StringUtil.GetOptions(Properties.Resources.JOURNAL_OPTIONS_SUBJECT_FMT);


        private ContactInfo   _contact;
        private string        _status = String.Empty;
        private bool          _error = false;

        public Dialer(ContactInfo contact) {
            _contact = contact;
        }

        public ContactInfo ContactInfo {
            get {
                return _contact;
            }
        }

        public void Dial() {
            VDialerConfiguration config = VDialerConfiguration.Instance;
            if (!config.ConfigurationValid) {
                System.Windows.Forms.MessageBox.Show(Properties.Resources.ERROR_MISSING_CONFIG, Properties.Resources.ERROR_MISSING_CONFIG_CAPTION, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Stop);
                return;
            }
            if (config.ShowDialDialog) {
                VDialerDialForm frm = new VDialerDialForm(this, config.ShowDialDialogAutoClose, config.ShowDialDialogWait);
                frm.Show();
            } else {
                InitiateCall();
                if (Error)
                    System.Windows.Forms.MessageBox.Show(_status, Properties.Resources.ERROR_CALL_CAPTION, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Stop);

            }
        }

        public void InitiateCall() {
            VDialerConfiguration config  = VDialerConfiguration.Instance;
            String               number  = FormatNumber(_contact.SelectedItem.Number);


            try {
                Click2Call.MakeCall(config.UserName, config.Password, config.OwnNumber, number);
                _status = Properties.Resources.DIALER_STATUS_COMPLETED;
                _error  = false;

                if (config.CreateJournal)
                    CreateJournal();
            } catch (Exception e) {
                _status = e.Message;
                _error = true;
            }
        }


        public void Clear() {
            _status = String.Empty;
            _error  = false;
        }

        public string Status { get { return _status; } }

        public bool Error { get { return _error; } }

        private void CreateJournal() {
            VDialerJournalOptions options = VDialerConfiguration.Instance.JournalOptions;
            OOutlook.JournalItem  journal = OutlookManager.CreateJournal(options.Folder);

            if (!String.IsNullOrEmpty(options.EntryType))
                journal.Type = options.EntryType;
            if (options.LinkContact)
                journal.Links.Add(_contact.ContactItem);
            if (options.CopyCompany)
                journal.Companies = _contact.ContactItem.CompanyName;
            if (options.MarkPrivate)
                journal.Sensitivity = Microsoft.Office.Interop.Outlook.OlSensitivity.olPrivate;

            if ((!String.IsNullOrEmpty(options.Category)) && (!("None".Equals(options.Category, StringComparison.CurrentCultureIgnoreCase)))) {
                if ("Copy".Equals(options.Category, StringComparison.CurrentCultureIgnoreCase))
                    journal.Categories = _contact.ContactItem.Categories;
                else {
                    journal.Categories = OutlookManager.Categories[options.Category].Name;
                }
            }

            StringUtil.Option format = Array.Find<StringUtil.Option>(subjectfmt, delegate(StringUtil.Option opt) { return opt.Id.Equals(options.Subject); });
            if (format != null) {
                journal.Subject = String.Format(format.Description, (object)_contact.SelectedItem.Number, (object)_contact.SelectedItem.Type, (object)_contact.ContactItem.FileAs);
            }

            journal.Body = String.Format(Properties.Resources.JOURNAL_OPTIONS_BODY_FMT, (object)_contact.SelectedItem.Number, (object)_contact.SelectedItem.Type, (object)_contact.ContactItem.FileAs);

            if (options.AutoSave)
                journal.Save();

            if (options.OpenForm)
                journal.Display(false);

        }

        

        private string FormatNumber(string number) {
            VDialerConfiguration config = VDialerConfiguration.Instance;
            
            number.Trim();

            number = number.ToLower();

            if (config.IgnoreExtension && (extexpr.IsMatch(number))) {
                Match match = extexpr.Match(number);
                number = number.Substring(0, match.Index);
            }

            if (number.StartsWith("+" + config.CountryCode + " ")) {
                number = number.Substring(config.CountryCode.Length + 2);
            } else if (number.StartsWith("+")) {
                number = number.Replace("+", config.InternationalPrefix);
            }

            if (number.StartsWith("(") && (!String.IsNullOrEmpty(config.LongDistancePrefix)))
                number = config.LongDistancePrefix + number;

            char[] narr = number.ToCharArray();
            StringBuilder buf = new StringBuilder();
            for (int i = 0, j = narr.Length; i < j; i++) {
                if (expr.IsMatch(narr[i].ToString()))
                    buf.Append(narr[i]);

            }
            return buf.ToString().Trim();
        }
        

    }
}
